﻿// ===============================================================================
// Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
// 作者:焦元义
// ===============================================================================

using System;
using System.Threading.Tasks;
using XCI.Extensions;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Sys.Filter;
using XCI.Windows;
using XCI.Helper;
using XCI.Core;

namespace XCI.Sys.Forms
{
    public partial class DicManagerControl : BaseUserControl
    {
        private SysDicCategory _category;
        private readonly bool allowInsert = SysApp.Permit("sys.dic.insert");
        private readonly bool allowUpdate = SysApp.Permit("sys.dic.update");
        private readonly bool allowDelete = SysApp.Permit("sys.dic.delete");
        private readonly bool allowExport = SysApp.Permit("sys.dic.export");

        public DicManagerControl()
        {
            InitializeComponent();
        }

        public async Task SetCategoryAsync(SysDicCategory category)
        {
            _category = category;
            await LoadAsync();
            dicTree.ExpandAll();
        }

        private Task LoadAsync()
        {
            return Mutex.EndAsync(() => dicTree.LoadAsync());
        }

        private void ShowEditForm(EditFormArgs args)
        {
            if (_category == null) throw new ArgumentException("category");
            args.Code = _category.Code;
            var editForm = new FrmDicEdit(args);
            editForm.ShowDialogOk(async () =>
            {
                await dicTree.LoadAsync();
            });
        }

        private void DicManagerControl_Load(object sender, EventArgs e)
        {
            dicTree.StateImageList = SysDicService.Instance.GetDicImageCollection();
            Mutex.Begin(() => editStatus.SelectedIndex = 0);
        }

        /// <summary>
        /// 搜索按钮点击事件
        /// </summary>
        private async void btnSearch_Click(object sender, EventArgs e)
        {
            await LoadAsync();
            dicTree.ApplyFindFilter(editKey.Text.Trim());
        }

        /// <summary>
        /// 状态发生变化事件
        /// </summary>
        private async void statusCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            await LoadAsync();
        }

        /// <summary>
        /// 新建根事件
        /// </summary>
        private void BtnNewRoot_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(EditFormArgs.CreateTree(R.RootTreeId));
        }

        /// <summary>
        /// 批量新建事件
        /// </summary>
        private void BtnNewBatch_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_category == null) throw new ArgumentException("category");
            var editForm = new FrmDicBatchEdit(new EditFormArgs { Created = true, Code = _category.Code, ParentId = R.RootTreeId });
            editForm.ShowDialogOk(async () =>
            {
                await dicTree.LoadAsync();
                dicTree.ExpandAll();
            });
        }

        /// <summary>
        /// 新建事件
        /// </summary>
        private void btnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(EditFormArgs.CreateTree(dicTree.SelectedId));
        }

        /// <summary>
        /// 修改事件
        /// </summary>
        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(EditFormArgs.EditTree(dicTree.SelectedId, ((SysDic)dicTree.Selected).ParentId));
        }

        /// <summary>
        /// 复制事件
        /// </summary>
        private async void btnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBoxHelper.ShowWarnYesNo("确定要复制当前选中的数据吗?") != System.Windows.Forms.DialogResult.Yes) return;
            await SysDicService.Instance.CopyDicAsync(dicTree.SelectedId);
            await dicTree.LoadAsync();
        }

        /// <summary>
        /// 删除事件
        /// </summary>
        private async void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            await dicTree.DeleteCheckedAsync();
        }

        private async void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var filter = dicTree.GetFilter();
            await App.Excel.ExportFileDialogAsync((path, fields) => SysDicService.Instance.ExportAsync(path, filter as SysDicFilter), "系统数据字典", this);
        }

        private void btnProperty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new FrmDicDetails(dicTree).ShowDialogOk();
        }

        private async void btnRefreshCache_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            await SysDicService.Instance.RefreshServiceCacheAsync();
            SysDicService.Instance.RefreshLocalCache();
            await dicTree.LoadAsync();
            MessageBoxHelper.ShowMessage("缓存刷新成功");
        }

        private async void RepositoryEditStatus_CheckedChanged(object sender, EventArgs e)
        {
            var edit = dicTree.ActiveEditor;
            var col = dicTree.FocusedColumn;
            if (col.FieldName.Equals(nameof(SysDic.Status)))
            {
                await SysDicService.Instance.UpdateDicStatusAsync(dicTree.SelectedId, edit.EditValue.ToBool());
            }
        }

        private void Tree_LoadData(object sender, LoadTreeDataEventArgs e)
        {
            e.Task = async () => await SysDicService.Instance.SelectDicListAsync(e.Filter as SysDicFilter);
        }

        private void Tree_DetectFilter(object sender, DetectTreeFilterObjectEventArgs e)
        {
            if (_category == null) throw new ArgumentException("category");
            e.Filter = App.ContainerData.GetModel(layoutGroupFilter, new SysDicFilter { Code = _category.Code });
        }

        private void Tree_DeleteData(object sender, DeleteDataEventArgs e)
        {
            e.Task = () => SysDicService.Instance.DeleteDicAsync(dicTree.CheckedIds);
        }

        private void Tree_RowSelectionChanged(object sender, EventArgs e)
        {
            var isSingle = !dicTree.HasMultiSelected && !dicTree.HasMultiChecked && dicTree.HasSelected;
            btnNewRoot.Enabled = allowInsert;
            btnNew.Enabled = allowInsert;
            btnEdit.Enabled = isSingle && allowUpdate;
            btnCopy.Enabled = isSingle && allowInsert;
            btnDelete.Enabled = dicTree.HasChecked && allowDelete;
            btnExport.Enabled = dicTree.HasData && allowExport;
            btnProperty.Enabled = isSingle;
            btnSearch.Enabled = true;
        }

        private async void Tree_NodeDragChangedChanged(object sender, NodeDragChangedEventArgs e)
        {
            await SysDicService.Instance.UpdateDicDndAsync(e.ChangedData);
        }

        private void Tree_GetStateImage(object sender, DevExpress.XtraTreeList.GetStateImageEventArgs e)
        {
            e.NodeImageIndex = SysDicService.Instance.GetDicNodeImageIndex(e.Node);
        }

    }
}